const loaded = {}
const loadJs = (url) => {
  const name = url && url.split('?')[0].split('/').reverse()[0]
  const id = 'js_' + name
  return new Promise((resolve, reject) => {
    if (loaded[id]) {
      return resolve()
    }
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.async = true
    script.src = url
    script.id = id
    script.onload = () => {
      loaded[id] = true
      resolve()
    }
    script.onerror = () => {}
    document.body.appendChild(script)
  })
}

/**
 * 动态加载样式
 */
const loadCss = (url) => {
  const name = url && url.split('?')[0].split('/').reverse()[0]
  const id = 'css_' + name
  return new Promise((resolve, reject) => {
    if (loaded[id]) {
      return resolve()
    }
    var link = document.createElement('link')
    link.type = 'text/css'
    link.rel = 'stylesheet'
    link.href = url
    link.id = id
    link.onload = () => {
      loaded[id] = true
      resolve()
    }
    link.onerror = () => {
      reject()
    }
    document.head.appendChild(link)
  })
}

export { loadJs, loadCss }
